<template>
  <div class="app-container">
    <div class="detail-page">
      <!-- 标题栏 -->
      <div class="page-header">
        <el-button type="primary" @click="handleBack" class="back-button">
          <el-icon><arrow-left /></el-icon> 返回
        </el-button>
        <h2 class="page-title">请假申请详情</h2>
      </div>

      <!-- 基本信息和操作记录区域 -->
      <div class="info-layout">
        <!-- 左侧：基本信息 + 申请信息 + 销假记录 -->
        <div class="left-panel">
          <!-- 基本信息 -->
          <div class="info-section">
            <div class="section-title">基本信息</div>
            <div class="info-grid">
              <div class="info-item">
                <label class="info-label">单据编号</label>
                <div class="info-value">{{ leaveDetail.extraField1 }}</div>
              </div>
              <div class="info-item">
                <label class="info-label">老人姓名</label>
                <div class="info-value">{{ elderInfo.name }}</div>
              </div>
              <div class="info-item">
                <label class="info-label">老人身份证号</label>
                <div class="info-value">{{ elderInfo.idCard }}</div>
              </div>
              <div class="info-item">
                <label class="info-label">联系方式</label>
                <div class="info-value">{{  elderInfo.contact }}</div>
              </div>

              <div class="info-item">
                <label class="info-label">入住床位</label>
                <div class="info-value">{{ leaveDetail.bedNumber }}</div>
              </div>

            </div>
          </div>

          <!-- 申请信息 -->
          <div class="info-section">
            <div class="section-title">申请信息</div>
            <div class="info-grid">
              <div class="info-item full-width">
                <label class="info-label">陪同人</label>
                <div class="info-value">{{ leaveDetail.companionName }}</div>
              </div>
              <div class="info-item full-width" v-if="leaveDetail.companion && leaveDetail.companion !== '无'">
                <label class="info-label">陪同人姓名</label>
                <div class="info-value">{{ leaveDetail.companionName }}</div>
              </div>
              <div class="info-item full-width" v-if="leaveDetail.companion && leaveDetail.companion !== '无'">
                <label class="info-label">陪同人联系方式</label>
                <div class="info-value">{{ leaveDetail.companionPhone }}</div>
              </div>
              <div class="info-item full-width">
                <label class="info-label">请假周期</label>
                <div class="info-value">{{ formatDateRange(leaveDetail.leaveStartTime, leaveDetail.expectedEndTime) }}</div>
              </div>
              <div class="info-item">
                <label class="info-label">请假天数</label>
                <div class="info-value">{{leaveDetail.actualLeaveDays}}天</div>
              </div>
              <div class="info-item full-width">
                <label class="info-label">请假原因</label>
                <div class="info-value">{{ leaveDetail.leaveReason }}</div>
              </div>
              <div class="info-item">
                <label class="info-label">申请人</label>
                <div class="info-value">{{ userInfo.userName || leaveDetail.sysUser?.userName || leaveDetail.creator }}</div>
              </div>
              <div class="info-item">
                <label class="info-label">申请时间</label>
                <div class="info-value">{{ parseTime(leaveDetail.createTime) }}</div>
              </div>
            </div>
          </div>

          <!-- 销假记录 -->
          <div v-if="leaveDetail.leaveStatus === '1'" class="info-section">
            <div class="section-title">
              <el-icon class="status-icon"><check /></el-icon>
              销假记录
            </div>
            <div class="info-grid">
              <div class="info-item">
                <label class="info-label">状态</label>
                <div class="info-value status-returned">已返回</div>
              </div>
              <div class="info-item">
                <label class="info-label">实际返回时间</label>
                <div class="info-value">{{ parseTime(leaveDetail.actualEndTime) }}</div>
              </div>
              <div class="info-item">
                <label class="info-label">实际请假天数</label>
                <div class="info-value">{{ leaveDetail.actualLeaveDays }}天</div>
              </div>
              <div class="info-item full-width">
                <label class="info-label">备注</label>
                <div class="info-value">{{ leaveDetail.actualReturnRemark }}</div>
              </div>
              <div class="info-item">
                <label class="info-label">销假人</label>
                <div class="info-value">{{ leaveDetail.returnOperator || userInfo.userName || '系统' }}</div>
              </div>
              <div class="info-item">
                <label class="info-label">销假时间</label>
                <div class="info-value">{{ parseTime(leaveDetail.actualEndTime) }}</div>
              </div>
            </div>
          </div>
        </div>

        <!-- 右侧：操作记录 -->
        <div class="right-panel">
          <div class="record-section">
            <div class="section-title">操作记录</div>
            <div class="record-list">
              <div v-for="record in operationRecords" :key="record.id" class="record-item">
                <div class="record-step">
                  <div class="step-number">{{ record.step }}</div>
                </div>
                <div class="record-content">
                  <div class="record-action">{{ record.action }}</div>
                  <div class="record-user">{{ record.user }}({{ record.status }})</div>
                  <div class="record-time">{{ parseTime(record.time) }}</div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { getRequest } from '@/api/system/request'
import { getElderly } from '@/api/system/elderly' // 导入获取老人信息的API
import { getBed } from '@/api/system/bed' // 导入获取床位信息的API
import { getUser } from '@/api/system/user' // 导入获取用户信息的API
import { listRecord } from '@/api/system/record' // 导入审批记录API
import { parseTime } from '@/utils/ruoyi'

const router = useRouter()
const route = useRoute()
const leaveDetail = ref({})
const operationRecords = ref([])
const elderInfo = ref({}) // 新增一个专门存储老人详细信息的变量
const userInfo = ref({}) // 新增一个专门存储申请人信息的变量

// 获取请假详情
const getLeaveDetail = async () => {
  const id = route.query.id
  if (!id) {
    return
  }
  try {
    const response = await getRequest(id)
    leaveDetail.value = response.data
    
    // 如果有老人外键ID，获取老人详细信息
    if (leaveDetail.value.elderlyId) {
      await getElderlyDetail(leaveDetail.value.elderlyId)
    }
    
    // 如果有用户外键ID，获取申请人详细信息
    if (leaveDetail.value.creator || leaveDetail.value.sysUserId) {
      await getUserDetail(leaveDetail.value.creator || leaveDetail.value.sysUserId)
    }
    
    // 处理操作记录数据（从后端获取真实审批记录）
    await generateOperationRecords()
  } catch (error) {
    console.error('获取请假详情失败', error)
  }
}

// 通过老人ID获取老人详细信息
const getElderlyDetail = async (elderlyId) => {
  try {
    const response = await getElderly(elderlyId)
    elderInfo.value = response.data
    
    // 获取床位信息
    let bedNo = ''
    const elderly = response.data
    
    // 情况1: 如果嵌套的bed对象存在且有bedNo
    if (elderly.bed && elderly.bed.bedNo) {
      bedNo = elderly.bed.bedNo
    }
    // 情况2: 如果直接有bedNo字段
    else if (elderly.bedNo) {
      bedNo = elderly.bedNo
    }
    // 情况3: 如果有bed_id或bedId，使用它调用bed API获取床位号
    else if (elderly.bed_id || elderly.bedId) {
      const bedId = elderly.bed_id || elderly.bedId
      try {
        const bedResponse = await getBed(bedId)
        if (bedResponse && bedResponse.data && bedResponse.data.bedNo) {
          bedNo = bedResponse.data.bedNo
        }
      } catch (error) {
        console.warn('获取床位信息失败，床ID:', bedId, error)
      }
    }
    
    // 将床位号设置到 leaveDetail 中，以便页面显示
    if (bedNo) {
      leaveDetail.value.bedNumber = bedNo
    }
  } catch (error) {
    console.error('获取老人信息失败', error)
  }
}

// 通过用户ID获取申请人详细信息
const getUserDetail = async (creator) => {
  try {
    const response = await getUser(creator)
    userInfo.value = response.data
  } catch (error) {
    console.error('获取申请人信息失败', error)
  }
}

// 生成操作记录 - 从后端获取真实的审批记录数据
const generateOperationRecords = async () => {
  const businessId = leaveDetail.value.id
  if (!businessId) {
    console.log('没有业务ID，跳过加载操作记录')
    return
  }
  
  try {
    // 调用审批记录API获取真实数据
    const params = {
      bussniessId: businessId,
      type: 2 // 2表示请假类型
    }
    const response = await listRecord(params)
    
    if (response && response.rows && response.rows.length > 0) {
      // 按步骤号排序
      const recordList = response.rows.sort((a, b) => a.stepNo - b.stepNo)
      
      // 转换为操作记录格式
      const records = recordList.map(record => {
        // 根据审批状态判断显示文本
        let statusText = '已通过'
        if (record.auditStatus === 2) {
          statusText = '已拒绝'
        } else if (record.auditStatus === 1) {
          statusText = '已通过'
        }
        
        return {
          id: record.id,
          step: record.stepNo,
          action: record.currentStep || '操作',
          user: record.approverName || '系统',
          status: statusText,
          time: record.finishTime || record.createTime
        }
      })
      
      // 如果已销假，添加销假记录
      if (leaveDetail.value.leaveStatus === '1') {
        records.push({
          id: records.length + 1,
          step: records.length + 1,
          action: '销假登记',
          user: leaveDetail.value.returnOperator || userInfo.value.userName || '系统',
          status: '已完成',
          time: leaveDetail.value.actualEndTime
        })
      }
      
      operationRecords.value = records
    } else {
      // 如果没有审批记录，使用基本的申请记录
      const records = [
        {
          id: 1,
          step: 1,
          action: '发起申请-申请请假',
          user: userInfo.value.userName || leaveDetail.value.sysUser?.userName || '系统',
          status: '已提交',
          time: leaveDetail.value.createTime || new Date()
        }
      ]
      
      // 如果已销假，添加销假记录
      if (leaveDetail.value.leaveStatus === '1') {
        records.push({
          id: 2,
          step: 2,
          action: '销假登记',
          user: leaveDetail.value.returnOperator || userInfo.value.userName || '系统',
          status: '已完成',
          time: leaveDetail.value.actualEndTime
        })
      }
      
      operationRecords.value = records
    }
  } catch (error) {
    console.error('获取操作记录失败', error)
    // 出错时使用基本记录
    operationRecords.value = [
      {
        id: 1,
        step: 1,
        action: '发起申请-申请请假',
        user: userInfo.value.userName || '系统',
        status: '已提交',
        time: leaveDetail.value.createTime || new Date()
      }
    ]
  }
}

// 格式化日期范围
const formatDateRange = (start, end) => {
  if (!start || !end) return ''
  return `${parseTime(start, '{y}-{m}-{d} {h}:{i}:{s}')} —— ${parseTime(end, '{y}-{m}-{d} {h}:{i}:{s}')}`
}

// 返回上一页
const handleBack = () => {
  router.back()
}

// 组件挂载时获取数据
onMounted(() => {
  getLeaveDetail()
})
</script>

<style scoped>
.detail-page {
  background: #f5f5f5;
  min-height: 100vh;
  padding: 20px;
}

.page-header {
  display: flex;
  align-items: center;
  margin-bottom: 30px;
  padding-bottom: 15px;
  border-bottom: 1px solid #e8e8e8;
}

.back-button {
  margin-right: 20px;
}

.page-title {
  font-size: 20px;
  font-weight: bold;
  color: #333;
  margin: 0;
}

.info-layout {
  display: grid;
  grid-template-columns: 1fr 400px;
  gap: 30px;
  max-width: 1200px;
  margin: 0 auto;
}

.left-panel {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.right-panel {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.info-section {
  background: white;
  border-radius: 8px;
  padding: 25px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  border: 1px solid #f0f0f0;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 20px;
  padding-left: 8px;
  border-left: 4px solid #1890ff;
  color: #333;
  display: flex;
  align-items: center;
  gap: 8px;
}

.status-icon {
  color: #1890ff;
}

.info-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 15px;
}

.info-item {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.info-item.full-width {
  grid-column: 1 / -1;
}

.info-label {
  font-size: 14px;
  color: #666;
  font-weight: 500;
}

.info-value {
  font-size: 14px;
  color: #333;
  background: #fafafa;
  padding: 10px 15px;
  border-radius: 4px;
  border: 1px solid #e8e8e8;
  min-height: 40px;
  display: flex;
  align-items: center;
}

.info-value.status-returned {
  color: #52c41a;
  font-weight: 500;
}

.record-section {
  background: white;
  border-radius: 8px;
  padding: 25px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  border: 1px solid #f0f0f0;
}

.record-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.record-item {
  display: flex;
  align-items: flex-start;
  gap: 15px;
  padding: 15px 0;
  position: relative;
}

.record-item:not(:last-child)::after {
  content: '';
  position: absolute;
  left: 15px;
  bottom: 0;
  width: 2px;
  height: 15px;
  background: #1890ff;
}

.record-step {
  flex-shrink: 0;
  position: relative;
}

.step-number {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  background: #1890ff;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  font-size: 14px;
  border: 2px solid #1890ff;
  position: relative;
  z-index: 2;
}

.record-content {
  flex: 1;
}

.record-action {
  font-size: 14px;
  color: #333;
  font-weight: 500;
  margin-bottom: 5px;
}

.record-user {
  font-size: 13px;
  color: #666;
  margin-bottom: 3px;
}

.record-time {
  font-size: 12px;
  color: #999;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .info-layout {
    grid-template-columns: 1fr;
  }
  
  .info-grid {
    grid-template-columns: 1fr;
  }
}
</style>